﻿using Goooodbye.Core.Repositories;
using Goooodbye.Core.Services;
using Goooodbye.Core.Services.Impl;
using Goooodbye.Infrastructure.Repositories;
using Microsoft.Owin;
using Owin;
using SimpleInjector;
using SimpleInjector.Integration.WebApi;
using SimpleInjector.Lifestyles;
using System;
using System.Data;
using System.Data.SQLite;
using System.Web.Http;

[assembly: OwinStartup(typeof(Goooodbye.Presentation.WebApi.App_Start.Startup))]
namespace Goooodbye.Presentation.WebApi.App_Start
{
    public class Startup
    {
        private static readonly string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}app_data.db;Version=3;";

        public void Configuration(IAppBuilder app)
        {
            // SimpleInjector configuration
            var container = new Container();
            container.Options.ResolveUnregisteredConcreteTypes = true;  // REQUIRED
            container.Register<IDbConnection>(() => new SQLiteConnection(connectionString), Lifestyle.Singleton);
            container.Register<IDictRepository, DictRepository>();
            container.Register<IDictService, DictService>();
            container.Verify();
            app.Use(async (context, next) =>
            {
                using (AsyncScopedLifestyle.BeginScope(container))
                {
                    await next();
                }
            });

            // Web API configuration
            HttpConfiguration config = new HttpConfiguration();
            config.EnableCors();
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "{controller}/{action}",
                defaults: new { controller = "Index", action = "Index" }
            );
            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); // REQUIRED
            app.UseWebApi(config);
        }
    }
}
